package com.engineering.elink.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.co.FollowCo;
import com.engineering.elink.common.Pagination;
import com.engineering.elink.dao.FollowMapper;
import com.engineering.elink.dao.UserMapper;
import com.engineering.elink.domain.Follow;
import com.engineering.elink.service.FollowService;

@Service
public class FollowServiceImpl implements FollowService{

	@Autowired
	private FollowMapper followMapper;
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public boolean checkFollow(String userId, String followUserId) {
		if (!userId.equals(followUserId)) {
			Follow follow = followMapper.selectByUserIdAndFollowUserId(userId, followUserId);
			if (follow != null) {
				return true;
			}
		}
		return false;
	}

	@Override
	public synchronized boolean follow(String userId, String followUserId) {
		Object user = userMapper.selectByUserId(userId);
		Object followUser = userMapper.selectByUserId(followUserId);
		if (userId.equals(followUserId) || user == null || followUser == null) {
			return false;
		}
		Follow followInSql = followMapper.selectByUserIdAndFollowUserId(userId, followUserId);
		if (followInSql != null) {
			followMapper.deleteByPrimaryKey(followInSql.getFollowId());
		}else {
			Follow follow = new Follow();
			follow.setCreateTime(new Date());
			follow.setFollowUserId(followUserId);
			follow.setUserId(userId);
			followMapper.insert(follow);
		}
		return true;
	}

	@Override
	public Map<String, Object> getFollowList(FollowCo followCo) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", followMapper.selectFollowList((followCo)));
		map.put("Pagination", new Pagination(followCo, followMapper.selectFollowListCount(followCo)));
		return map;
	}

	@Override
	public Map<String, Object> getByFollowList(FollowCo followCo) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", followMapper.selectByFollowList((followCo)));
		map.put("Pagination", new Pagination(followCo, followMapper.selectByFollowListCount(followCo)));
		return map;
	}

	@Override
	public Map<String, Object> getBothFollowList(FollowCo followCo) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", followMapper.selectBothFollowList((followCo)));
		map.put("Pagination", new Pagination(followCo, followMapper.selectBothFollowListCount(followCo)));
		return map;
	}

}
